package com.stone.stoneanswer.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.stone.stoneanswer.constant.CommonConstant;
import com.stone.stoneanswer.model.dto.question.QuestionGetRequest;
import com.stone.stoneanswer.model.entity.*;
import com.stone.stoneanswer.model.vo.AnswerResultVO;
import com.stone.stoneanswer.model.vo.QuestionVO;
import com.stone.stoneanswer.model.vo.UserVO;
import com.stone.stoneanswer.service.QuestionService;
import com.stone.stoneanswer.mapper.QuestionMapper;
import com.stone.stoneanswer.service.UserService;
import com.stone.stoneanswer.utils.SqlUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 35431
 * @description 针对表【question(题目)】的数据库操作Service实现
 * @createDate 2025-02-04 15:21:01
 */
@Service
public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question>
        implements QuestionService {

    @Resource
    private UserService userService;

    @Override
    public QuestionVO getQuestionVO(Question question, HttpServletRequest request) {
        QuestionVO questionVO = QuestionVO.objToVo(question);
        // 关联查询用户信息
        Long userId = question.getUserId();
        User user = null;
        if (userId != null && userId > 0) {
            user = userService.getById(userId);
        }
        UserVO userVO = userService.getUserVO(user);
        questionVO.setUser(userVO);
        // TODO 获取用户的点赞，收藏状态
        User loginUser = userService.getLoginUserPermitNull(request);
        if (loginUser != null) {
            questionVO.setIsFavour(true);
            questionVO.setIsThumb(true);
        }
        return questionVO;
    }

    @Override
    public QueryWrapper<Question> getQueryWrapper(QuestionGetRequest questionGetRequest) {
        QueryWrapper<Question> queryWrapper = new QueryWrapper<>();
        if (questionGetRequest == null) {
            return queryWrapper;
        }
        String searchText = questionGetRequest.getSearchText();
        Long questionId = questionGetRequest.getId();
        String content = questionGetRequest.getContent();
        List<String> tags = questionGetRequest.getTags();
        Long userId = questionGetRequest.getUserId();
        String sortOrder = questionGetRequest.getSortOrder();
        String sortField = questionGetRequest.getSortField();

        // 拼接查询条件
        if (StringUtils.isNotBlank(searchText)) {
            queryWrapper.and(qw -> qw.like("title", searchText).or().like("content", searchText));
        }
        queryWrapper.like(StringUtils.isNotBlank(content), "content", content);
        if (CollUtil.isNotEmpty(tags)) {
            for (String tag : tags) {
                queryWrapper.like("tags", "\"" + tag + "\"");
            }
        }
        queryWrapper.eq(ObjectUtils.isNotEmpty(questionId), "id", questionId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    @Override
    public Page<QuestionVO> getQuestionVOPage(Page<Question> questionPage, HttpServletRequest request) {
        List<Question> questionList = questionPage.getRecords();
        Page<QuestionVO> questionVOPage = new Page<>(questionPage.getCurrent(), questionPage.getSize(), questionPage.getTotal());
        if (CollUtil.isEmpty(questionList)) {
            return questionVOPage;
        }
        // 1. 关联查询用户信息
        Set<Long> userIdSet = questionList.stream().map(Question::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));

        // TODO 获取用户点赞，收藏状态

        // TODO 填充数据
        // 填充信息
        List<QuestionVO> questionVOList = questionList.stream().map(question -> {
            QuestionVO questionVO = QuestionVO.objToVo(question);
            Long userId = question.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            questionVO.setUser(userService.getUserVO(user));
            // TODO 设置用户点赞，收藏状态信息
            return questionVO;
        }).collect(Collectors.toList());
        questionVOPage.setRecords(questionVOList);
        return questionVOPage;
    }

    @Override
    public List<QuestionVO> getQuestionFromBank(Long bankId) {
        List<Question> list = list(new QueryWrapper<Question>().lambda().eq(Question::getQuestionBankId, bankId));
        return list.stream().map(QuestionVO::objToVo).collect(Collectors.toList());
    }

    @Override
    public List<QuestionVO> getQuestionFromBankByType(Long bankId, Integer type) {
        List<Question> list = list(new QueryWrapper<Question>().lambda().eq(Question::getQuestionBankId, bankId).eq(Question::getType ,type));
        return list.stream().map(QuestionVO::objToVo).collect(Collectors.toList());
    }
}




